import { MailItem, Item } from "../shared/face/index";
import sdk from "../core";
import { bagService } from "./BagService";
import common from "../core/tool/common";

/**
 * 邮件服务类
 * 职责：
 * 1. 邮件列表管理
 * 2. 邮件发送和接收
 * 3. 邮件物品处理
 * 4. 邮件状态管理
 */
export class MailService {

    /**
     * 获取用户邮件列表
     * @param userId 用户ID
     * @returns 邮件列表
     */
    static async getUserMails(userId: string): Promise<{
        success: boolean;
        message: string;
        mails: MailItem[];
        unreadCount: number;
    }> {
        try {
            const mails = await sdk.mail.pull(userId);
            const unreadCount = mails.filter((mail: MailItem) => !mail.read).length;
            
            return {
                success: true,
                message: `获取到 ${mails.length} 封邮件`,
                mails,
                unreadCount
            };
        } catch (error) {
            return {
                success: false,
                message: '获取邮件失败',
                mails: [],
                unreadCount: 0
            };
        }
    }

    /**
     * 获取邮件数量
     * @param userId 用户ID
     * @returns 邮件数量
     */
    static async getMailCount(userId: string): Promise<{
        success: boolean;
        message: string;
        count: number;
    }> {
        try {
            const count = await sdk.mail.getMailCount(userId);
            
            return {
                success: true,
                message: `有 ${count} 封邮件`,
                count
            };
        } catch (error) {
            return {
                success: false,
                message: '获取邮件数量失败',
                count: 0
            };
        }
    }

    /**
     * 发送邮件
     * @param fromId 发件人ID
     * @param toId 收件人ID
     * @param title 邮件标题
     * @param content 邮件内容
     * @param items 附件物品
     * @param expireDays 过期天数
     * @returns 发送结果
     */
    static async sendMail(
        fromId: string,
        toId: string,
        title: string,
        content: string,
        items: Item[] = [],
        expireDays: number = 30
    ): Promise<{
        success: boolean;
        message: string;
    }> {
        try {
            await sdk.mail.send(fromId, toId, expireDays, title, content, items);
            
            return {
                success: true,
                message: '邮件发送成功'
            };
        } catch (error) {
            return {
                success: false,
                message: '邮件发送失败'
            };
        }
    }

    /**
     * 处理邮件物品领取
     * @param mail 邮件对象
     * @param currentBagItems 当前背包物品
     * @returns 领取结果
     */
    static processMailItems(mail: MailItem, currentBagItems: Item[]): {
        success: boolean;
        message: string;
        newBagItems: Item[];
        claimedItems: Item[];
    } {
        if (!mail.items || mail.items.length === 0) {
            return {
                success: false,
                message: '该邮件没有物品',
                newBagItems: currentBagItems,
                claimedItems: []
            };
        }
        
        let newBagItems = [...currentBagItems];
        const claimedItems: Item[] = [];
        
        // 逐个添加物品到背包
        for (const item of mail.items) {
            const addResult = bagService.addItem(newBagItems, item);
            if (addResult.success) {
                newBagItems = addResult.newBagItems;
                claimedItems.push(item);
            } else {
                return {
                    success: false,
                    message: addResult.message,
                    newBagItems: currentBagItems,
                    claimedItems: []
                };
            }
        }
        
        return {
            success: true,
            message: `成功领取 ${claimedItems.length} 个物品`,
            newBagItems,
            claimedItems
        };
    }

    /**
     * 格式化邮件内容用于显示
     * @param mail 邮件对象
     * @returns 格式化后的显示内容
     */
    static formatMailForDisplay(mail: MailItem): {
        title: string;
        content: string;
        hasItems: boolean;
        isExpired: boolean;
        timeInfo: string;
    } {
        const now = Date.now();
        const isExpired = mail.expire_time > 0 && mail.expire_time < now;
        
        // 时间信息
        const sendTime = new Date(mail.send_time).toLocaleString();
        let timeInfo = `发送时间: ${sendTime}`;
        
        if (mail.expire_time > 0) {
            const expireTime = new Date(mail.expire_time).toLocaleString();
            if (isExpired) {
                timeInfo += `\n已过期: ${expireTime}`;
            } else {
                timeInfo += `\n过期时间: ${expireTime}`;
            }
        }
        
        return {
            title: mail.title,
            content: mail.msg,
            hasItems: mail.items && mail.items.length > 0,
            isExpired,
            timeInfo
        };
    }

    /**
     * 获取邮件统计信息
     * @param mails 邮件列表
     * @returns 统计信息
     */
    static getMailStats(mails: MailItem[]): {
        totalMails: number;
        unreadMails: number;
        mailsWithItems: number;
        expiredMails: number;
        systemMails: number;
    } {
        const now = Date.now();
        
        return {
            totalMails: mails.length,
            unreadMails: mails.filter(mail => !mail.read).length,
            mailsWithItems: mails.filter(mail => mail.items && mail.items.length > 0).length,
            expiredMails: mails.filter(mail => mail.expire_time > 0 && mail.expire_time < now).length,
            systemMails: mails.filter(mail => mail.sys).length
        };
    }

    /**
     * 发送系统邮件
     * @param title 邮件标题
     * @param content 邮件内容
     * @param items 附件物品
     * @param expireDays 过期天数
     * @returns 发送结果
     */
    static async sendSystemMail(
        title: string,
        content: string,
        items: Item[] = [],
        expireDays: number = 30
    ): Promise<{
        success: boolean;
        message: string;
    }> {
        return this.sendMail('sys', 'all', title, content, items, expireDays);
    }

    /**
     * 发送奖励邮件
     * @param toId 收件人ID
     * @param title 邮件标题
     * @param content 邮件内容
     * @param items 奖励物品
     * @param expireDays 过期天数
     * @returns 发送结果
     */
    static async sendRewardMail(
        toId: string,
        title: string,
        content: string,
        items: Item[],
        expireDays: number = 30
    ): Promise<{
        success: boolean;
        message: string;
    }> {
        return this.sendMail('admin', toId, title, content, items, expireDays);
    }

    /**
     * 拉取新邮件
     * @param userId 用户ID
     * @returns 新邮件列表
     */
    static async pullNewMails(userId: string): Promise<{ newMails: MailItem[] }> {
        const newMails = await sdk.mail.pull(userId);
        return {
            newMails
        };
    }
} 